#!/usr/bin/python
# coding=utf-8

from peewee import *
from http import OpenerCookies
import json
import urllib

db = SqliteDatabase('people.db')

class BaseModel(Model):
    class Meta:
        database = db

class UserArgs(BaseModel):
    name = CharField(max_length=127)
    username = CharField(max_length=127)
    url = CharField(max_length=1024)
    cookies = TextField()
    params = TextField()
    class Meta:
        db_table = "user_args"
        primary_key = CompositeKey('name', 'username')
    def get_cookies(self):
        return json.loads(self.cookies)
    def set_cookies(self,cookies):
        self.cookies = json.dumps(cookies)
    def get_params(self):
        return json.loads(self.params)
    def set_params(self,params):
        self.params = json.dumps(params)

class Task(UserArgs):
    opener = OpenerCookies()
    parent = None
    def run(self):
        self.opener.loadCookies(self.cookies)
        data = self.parseData()
        if not isinstance(data,basestring):
            data = urllib.urlencode(data)
        resp = self.opener.open(self.url, data, self.parseHeaders())
        if self.check(resp.read(),resp.info()):
            self.cookies = self.opener.cookie.save()
            self.save()
            return True
        return False
    def check(self):
        return True
    def parseData(self):
        return self.get_params()
    def parseHeaders(self):
        return {}
        
     